package com.sec.etech.process.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sec.etech.common.constant.DBConstant;
import com.sec.etech.process.mapper.SppOperationStepMapper;
import com.sec.etech.process.mapper.SppRelSamMapper;
import com.sec.etech.process.model.SppOperationStep;
import com.sec.etech.process.model.SppRelSam;
import com.sec.etech.process.model.SppRouteStep;
import com.sec.etech.sys.util.DbUtil;
import org.openbpm.base.core.id.IdUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SppRelSamService extends ServiceImpl<SppRelSamMapper, SppRelSam> {

    @Resource
    SppRouteStepService sppRouteStepService;
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private SppOperationStepMapper sppOperationStepMapper;

    /**
     * 获取路线卡/工序卡 工步关联的技术规范
     *
     * @param targetId
     * @param targetType
     * @param stepId
     * @return
     */
    public List<SppRelSam> getRefSamList(Long targetId, Integer targetType, Long stepId) {
        return baseMapper.selectList(Wrappers.<SppRelSam>lambdaQuery()
                .eq(SppRelSam::getTargetId, targetId)
                .eq(SppRelSam::getTargetType, targetType)
                .eq(SppRelSam::getStepId, stepId)
                .eq(SppRelSam::getActive, 1)
                .orderByAsc(SppRelSam::getOrderby)
        );
    }

    /**
     * 获取路线卡/工序卡 工步关联的技术规范
     *
     * @param targetId
     * @param targetType
     * @param stepId
     * @return
     */
    public List<Map<String, Object>> getRefSams(Long targetId, Integer targetType, Long stepId) {
        String sql = "SELECT t1.sam_id AS samId,if(length(t2.sam_code)>0,REPLACE(trim( SUBSTRING_INDEX( t2.sam_code, '-', 1 ) ), ' ', '' ),t1.sam_code) AS samCode," +
                "if(length(t2.sam_name),t2.sam_name,t1.sam_name) AS samName,t2.status_id AS statusId," +
                "t2.status_name AS statusName,if(length(t2.type)>0,t2.type,t1.sam_type) AS samType " +
                "FROM spp_rel_sam t1 LEFT JOIN sam_secs_notsecs t2 ON t1.sam_id = t2.pk_id AND t1.sam_type = t2.type " +
                "WHERE t1.target_id = ? AND t1.target_type = ? AND t1.step_id = ? AND t1.active = 1 " +
                "ORDER BY t1.orderby ASC";
        return DbUtil.getJdbcTemplate(DBConstant.ETECH_SLAVE).queryForList(sql, targetId, targetType, stepId);
    }

    /**
     * 获取路线卡/工序卡 关联的技术规范
     *
     * @param ids
     * @param targetType
     * @return
     */
    public List<Map<String, Object>> getRefSams(List<Long> ids, Integer targetType) {
        String sql = "SELECT t1.sam_id AS samId,if(length(t2.sam_code)>0,REPLACE(trim( SUBSTRING_INDEX( t2.sam_code, '-', 1 ) ), ' ', '' ),t1.sam_code) AS samCode," +
                "if(length(t2.sam_name),t2.sam_name,t1.sam_name) AS samName,t2.status_id AS statusId," +
                "t2.status_name AS statusName,if(length(t2.type)>0,t2.type,t1.sam_type) AS samType,t4.partsnum,t4.partsname " +
                "FROM spp_rel_sam t1 LEFT JOIN sam_secs_notsecs t2 ON t1.sam_id = t2.pk_id AND t1.sam_type = t2.type ";
        if (targetType == 1) {
            sql += "LEFT JOIN spp_route_rev t3 on t3.route_rev_id = t1.target_id and t1.target_type =1 ";
        } else if (targetType == 2) {
            sql += "LEFT JOIN spp_operation_rev t3 on t3.op_rev_id = t1.target_id and t1.target_type =2 ";
        }
        sql += "LEFT JOIN prod_parts t4 on t4.partsid = t3.partsid " +
                "WHERE t1.target_id in({}) AND t1.target_type = {} AND t1.active = 1 " +
                "GROUP BY t1.sam_id " +
                "ORDER BY t1.orderby ASC";
        return jdbcTemplate.queryForList(StrUtil.format(sql, CollUtil.join(ids, ","), targetType));
    }

    /**
     * 更新关联标准
     *
     * @param targetId
     * @param targetType
     * @param stepId
     * @param jsonArray
     */
    public void updateRefSam(Long targetId, Integer targetType, Long stepId, JSONArray jsonArray) {
        List<String> samCodes = new ArrayList<>();
        List<String> samNames = new ArrayList<>();
        for (Object o : jsonArray) {
            JSONObject jsonObject = JSONUtil.parseObj(o);
            samCodes.add(jsonObject.getStr("samCode"));
            //只显示编号 且不要年份
            String samCode = jsonObject.getStr("samCode", "");
            if (samCode.indexOf("-") > -1) {
                samCode = samCode.substring(0, samCode.lastIndexOf("-"));
            }
            samNames.add(samCode);
        }
        List<String> oldSamCodes = new ArrayList<>();
        List<SppRelSam> updateList = getRefSamList(targetId, targetType, stepId);
        if (CollUtil.isNotEmpty(updateList)) {
            for (SppRelSam sppRelSam : updateList) {
                String samCode = String.valueOf(sppRelSam.getSamCode());
                oldSamCodes.add(samCode);
                int index = samCodes.indexOf(samCode);
                if (index > -1) {
                    JSONObject jsonObject = JSONUtil.parseObj(jsonArray.get(index));
                    sppRelSam.setOrderby(jsonObject.getInt("orderby"));
                } else {
                    sppRelSam.setActive(0);
                }
            }
            this.updateBatchById(updateList);
        }
        List<SppRelSam> addList = new ArrayList<>();
        for (Object o : jsonArray) {
            JSONObject jsonObject = JSONUtil.parseObj(o);
            String samId = jsonObject.getStr("samId");
            String samType = jsonObject.getStr("samType");
            String samCode = jsonObject.getStr("samCode");
            String samName = jsonObject.getStr("samName");
            Integer orderby = jsonObject.getInt("orderby");
            if (oldSamCodes.indexOf(samCode) == -1) {
                SppRelSam sppRelSam = new SppRelSam();
                sppRelSam.setRelSamId(IdUtil.getUId());
                sppRelSam.setTargetId(targetId);
                sppRelSam.setTargetType(targetType);
                sppRelSam.setStepId(stepId);
                sppRelSam.setSamId(Long.valueOf(samId));
                sppRelSam.setSamType(samType);
                sppRelSam.setSamCode(samCode);
                sppRelSam.setSamName(samName);
                if (orderby != null) {
                    sppRelSam.setOrderby(orderby);
                } else {
                    sppRelSam.setOrderby(jsonArray.indexOf(o) + 1);
                }
                sppRelSam.setActive(1);
                addList.add(sppRelSam);
            }
        }
        if (CollUtil.isNotEmpty(addList)) {
            this.saveBatch(addList);
        }
        if (targetType == 1) {
            SppRouteStep sppRouteStep = sppRouteStepService.getById(stepId);
            if (sppRouteStep != null) {
                sppRouteStep.setSams(CollUtil.isNotEmpty(samNames) ? CollUtil.join(samNames, "\n") : "");
                sppRouteStepService.updateById(sppRouteStep);
            }
        } else if (targetType == 2) {
            SppOperationStep sppOperationStep = sppOperationStepMapper.selectById(stepId);
            if (sppOperationStep != null) {
                sppOperationStep.setSams(CollUtil.isNotEmpty(samNames) ? CollUtil.join(samNames, "\n") : "");
                sppOperationStepMapper.updateById(sppOperationStep);
            }
        }

    }
}
